﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;

using Telerik.Blogs;
using Telerik.Cms.Engine;

namespace Telerik.Sitefinity.Services.Migration
{
	public partial class MigrationExportService : IMigrationExportService
	{
		public Message GetBlogsList()
		{
			List<MigrationItemContentDefinition> output = new List<MigrationItemContentDefinition>();

			foreach (KeyValuePair<string, ContentProviderBase> provider in m_AllProviders)
			{
				// Check if the provider is DefaultBlogProvider
				if (provider.Value is Telerik.Blogs.Data.DefaultBlogProvider)
				{
					string providerName = provider.Key;
					BlogManager blogManager = new BlogManager(providerName);

					IList blogs = blogManager.GetBlogs();
					AddGenericContentGuidToList(blogs, output, providerName, String.Empty);
				}
			}

			MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
			return Message.CreateMessage(ver, "GetBlogsListResponse", output);
		}

		public Message GetSingleBlog(Message blogDefinitionParam)
		{
			MigrationItemContentDefinition param = blogDefinitionParam.GetBody<MigrationItemContentDefinition>();

			BlogManager blogManager = new BlogManager(param.ProviderName);
			IBlog blog = blogManager.GetBlog(param.Id);

			MigrationBlog result = new MigrationBlog();
			result.AllowComments = blog.AllowComments;
			result.Author = blog.Author;
			result.BlogPage = blog.BlogPage;
			result.CommentsModeration = blog.CommentsModeration;
			result.DateCreated = blog.DateCreated;
			result.Description = blog.Description;
			result.Id = blog.ID;
			result.Name = blog.Name;
			result.Owner = blog.Owner;
			result.ProviderName = param.ProviderName;
			result.PostPage = blog.PostPage;

			if (blogManager.Content.Provider.AllowLocalization)
			{
				foreach (var culture in m_Cultures)
				{
					if (culture != m_DefaultCulture)
						System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(culture);

					IList blogPosts = blogManager.GetPosts(String.Empty, blog.ID);

					AddGenericContentToList(blogPosts, result.Posts, param.ProviderName, culture);
				}
			}
			else
			{
				IList blogPosts = blogManager.GetPosts(String.Empty, blog.ID);
				AddGenericContentToList(blogPosts, result.Posts, param.ProviderName, String.Empty);
			}

			MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
			return Message.CreateMessage(ver, "GetSingleBlogResponse", result);
		}
	}
}
